import { isEmptyArr, isArray, isNullOrEmpty } from './index';
import { post } from '@/utils/http/Axios';
import dayjs from 'dayjs';
import advancedFormat from 'dayjs/plugin/advancedFormat';
dayjs.extend(advancedFormat);
import { formatFilterItem } from './componentRequest/formatCondition.js';

import { MobileComponentKey } from '@/enums/index'

// 普通的图表
const generateCommonFieldMap = (xAxisRelations, linkageInfo) => {
  const { values } = linkageInfo;
  const fieldMap = {};
  // 多维度
  xAxisRelations.forEach((item, index) => {
    const filter = formatFilterItem(item);
    fieldMap[item.datasetFieldName] = {
      value: values[index] ?? '',
      dateFormat: filter?.dateFormat || '',
      active: true,
    };
  });
  return Promise.resolve(fieldMap);
};

// 表格
function generateTableFieldMap(xAxisRelations, legendRelations, linkageInfo) {
  const fieldMap = {};
  const { values, index, name } = linkageInfo;

  // 获取当前关联的relation
  let relations;
  // 明细表不存在legend，此次为交叉表
  if (legendRelations && legendRelations.length > 0) {
    relations = legendRelations;
  } else {
    relations = xAxisRelations;
  }

  if (!relations) {
    return fieldMap;
  }
  // name存在说明是排名轮播表，排名轮播表就只有一个维度
  if (name) {
    relations.forEach((item, subIndex) => {
      const filter = formatFilterItem(item);
      fieldMap[item.datasetFieldName] = {
        value: name,
        dateFormat: filter?.dateFormat || '',
        active: true
      };
    });
  } else if(isNullOrEmpty(index)){
    // 列下标index不存在说明是明细表点击操作项的情况
    relations.forEach((item, subIndex) => {
      const filter = formatFilterItem(item);
      fieldMap[item.datasetFieldName] = {
        value: values[subIndex],
        dateFormat: filter?.dateFormat || '',
        active: true
      };
    });
  } else {
    // 多维度
    relations.forEach((item, subIndex) => {
      const filter = formatFilterItem(item);
      fieldMap[item.datasetFieldName] = {
        value: values[subIndex],
        dateFormat: filter?.dateFormat || '',
        active: index === subIndex
      };
    });
  }

  return Promise.resolve(fieldMap);
}

// 地图
function generateMapFieldList(xAxisRelations, linkageInfo, xAxisMoreRelations = []) {
  const { tableInfo, values } = linkageInfo;
  // 处理飞线地图
  const { fromName, toName, name } = values || {};
  xAxisRelations.forEach(item => item.areaName = fromName || name);
  xAxisMoreRelations.forEach(item => item.areaName = toName);
  const promiseList = [];
  // ---------------地图维度
  for(const item of [...xAxisRelations, ...xAxisMoreRelations]) {
    const { areaName, datasetFieldName } = item;
    // 如果存在值，说明是拖拽的地区信息，需要取映射值
    if (areaName) {
      const params = {
        datasetId: tableInfo.type === 'APPLICATION_RESOURCES' ? null: Number(tableInfo.tableId),
        datasetFieldName: datasetFieldName,
        tableBizCode: tableInfo.type === 'APPLICATION_RESOURCES' ? tableInfo.tableId : tableInfo.tableBizCode,
        value: areaName
      };
      const url = '/data-analysis/api/v2/dataset/geography/lookup';  // 地理维度映射信息
      promiseList.push(new Promise((resolve, reject) => {
        post(url, params).then(response => {
          const { valueList = [] } = response.data;
          resolve({ value: isEmptyArr(valueList) ? areaName : valueList, datasetFieldName });
        })
      }));
    }
  }
  return Promise.all(promiseList).then(values => {
    const fieldMap = {};
    values.forEach(item => {
      fieldMap[item.datasetFieldName] = {
        value: item.value,
        dateFormat: '',
        active: true
      };
    });
    return Promise.resolve(fieldMap);
  });
}
/**
 * 根据点击图表信息，生成映射值
 * @param {*} componentRelationMap 图表的配置信息
 * @param {*} linkageInfo 用户点击图表传入的信息
 * @returns
 * {
 *   fieldA: {
 *      value: '小王',
 *      dateFormat: '' // 日期类型需要特别对待
 *   },
 *   fieldB: {
 *      value: '天工傲',
 *      dateFormat: '' // 日期类型需要特别对待
 *   },
 */
export const generateFieldMap = (componentRelationMap, linkageInfo) => {
  const { xAxis, legend, xAxisMap, yAxisComment, yAxisTitle, yAxisHide } = componentRelationMap;
  const xAxisRelations = xAxis?.relations;
  const legendRelations = legend?.relations;
  const { seriesType } = linkageInfo;
  // 表格的联动和跳转需要单独处理
  if (seriesType === 'table') {
    // 表格的fieldMap生成原理不一样，需要区分处理
    return generateTableFieldMap(xAxisRelations, legendRelations, linkageInfo);
  }
  // 地图的联动，需要获取地图的映射值
  if (seriesType === 'map') {
    // 飞线图有两个维度配置项，需要特殊处理，目前仅有飞线图特殊，后续特殊情况多的话，可改为策略模式
    return generateMapFieldList(xAxisRelations, linkageInfo, xAxisMap?.relations);
  }

  // 日期组件联动，下拉条件多选，需单独处理
  if ([
      'control_dateFilter',
      'control_dateRange',
      MobileComponentKey.UViewDateFilterPageMobile,
      MobileComponentKey.UViewDatePickerPageMobile,
      MobileComponentKey.UViewDateRangePageMobile
  ].includes(seriesType)) {
    return generateDateFieldList(xAxisRelations, linkageInfo);
  }
  // 文本组件联动，下拉条件多选，需单独处理
  if (['control_textFilter'].includes(seriesType)) {
    return generateTextFieldList(xAxisRelations, linkageInfo);
  }
  if (seriesType === MobileComponentKey.UViewSelectPageMobile) {
    return generateMobileSelectFieldList(xAxisRelations, linkageInfo);
  }
  // 级联筛选联动
  if (seriesType === 'control_cascaderFilter') {
    return generateCascaderFieldList(xAxisRelations, linkageInfo);
  }
  // 树形选择器
  if (['control_treeSelect', MobileComponentKey.UViewTreeSelectPageMobile].includes(seriesType)) {
    return generateTreeSelectFieldList(linkageInfo);
  }
  //移动端搜索框
  if (seriesType === 'uview_search_page_mobile') {
    return generateSearchFieldList(linkageInfo)
  }
  // 联动器
  if (seriesType === 'control_linkage') {
    return generateControlLinkageFieldList(xAxisRelations, linkageInfo);
  }
  // 评论组件
  if(seriesType === 'info_comment') {
    return generateInfoCommentFieldMap([...yAxisComment?.relations, ...yAxisTitle?.relations, ...yAxisHide?.relations], linkageInfo);
  }
  return generateCommonFieldMap(xAxisRelations, linkageInfo);
};


// 评论组件需要映射的值
function generateInfoCommentFieldMap(xAxisRelations, linkageInfo) {
  const { values } = linkageInfo;
  const fieldMap = {};
  let key = '';
  // 多维度
  xAxisRelations.forEach((item, index) => {
    const filter = formatFilterItem(item);
    fieldMap[item.datasetFieldName] = {
      value: values[item.datasetFieldName] ?? '',
      dateFormat: filter?.dateFormat || '',
      active: true,
    };
  });
  return Promise.resolve(fieldMap);

}
//移动端搜索框
function generateSearchFieldList(linkageInfo) {
  const { values, seriesType } = linkageInfo
  const fieldMap = {}
  fieldMap[seriesType] = {
    value: values,
    dateFormat: '',
    active: true
  }
  return Promise.resolve(fieldMap)
}
// 日期筛选组件需要映射的值
function generateDateFieldList(xAxisRelations, linkageInfo) {
  const { values, subType, seriesType } = linkageInfo;
  const selectDateRange = {
    date: {
      format: 'YYYY年MM月DD日',
      dateFormat: 'YYYY_MM_DD'
    },
    month: {
      format: 'YYYY年MM月',
      dateFormat: 'YYYY_MM'
    },
    year: {
      format: 'YYYY年',
      dateFormat: 'YYYY'
    },
    yearMonthDayHour: {
      format: 'YYYY年MM月DD日 HH时',
      dateFormat: 'YYYY_MM_DD_HH'
    },
    yearMonthDayHourMin: {
      format: 'YYYY年MM月DD日 HH时mm分',
      dateFormat: 'YYYY_MM_DD_HH_MM'
    },
    yearMonthDayHourMinSec: {
      format: 'YYYY年MM月DD日 HH时mm分ss秒',
      dateFormat: 'YYYY_MM_DD_HH_MM_SS'
    },
    quarter: {
      format: 'YYYY年Q季度',
      dateFormat: 'YYYY_QUARTER'
    }
  };
  let date = [];
  // 季度处理
  if (subType==='quarter') {
    if (Array.isArray(values)) {
      const result = [];
      values.forEach((value) => {
        if (value) {
          const [year, quarter] = value.split('Q');
          result.push(`${year}年${quarter}季度`)
        } else {
          result.push('')
        }
      })
      date = [result[0], result[1]];
    } else {
      let result = '';
      if (values) {
        const [year, quarter] = values.split('Q');
        result = `${year}年${quarter}季度`
      }
      date = [result, result];
    }
  } else {
    if (Array.isArray(values)) {
      date = [dayjs(values[0]).format(selectDateRange[subType].format), dayjs(values[1]).format(selectDateRange[subType].format)];
    } else {
      date = [dayjs(values).format(selectDateRange[subType].format), dayjs(values).format(selectDateRange[subType].format)];
    }
  }
  const fieldMap = {};
  fieldMap[seriesType] = {
    value: date,
    dateFormat: selectDateRange[subType].dateFormat,
    active: true
  };
  return Promise.resolve(fieldMap, linkageInfo);
}

// 文本筛选组件需要映射的值
function generateTextFieldList(xAxisRelations, linkageInfo) {
  const { name } = linkageInfo;
  const fieldMap = {};
  // 单维度
  xAxisRelations.forEach((item) => {
    const filter = formatFilterItem(item);
    fieldMap[item.datasetFieldName] = {
      value: name,
      dateFormat: filter?.dateFormat || '',
      active: true
    };
  });
  return Promise.resolve(fieldMap, linkageInfo);
}

// 移动端选择下拉
function generateMobileSelectFieldList(xAxisRelations, linkageInfo) {
  const { name, index } = linkageInfo;
  const fieldMap = {};
  const currentXAxis = xAxisRelations && xAxisRelations[index];
  const filter = formatFilterItem(currentXAxis);
  fieldMap[currentXAxis.datasetFieldName] = {
    value: name,
    dateFormat: filter?.dateFormat || '',
    active: true
  };
  return Promise.resolve(fieldMap, linkageInfo);
}
// 级联筛选组件需要映射的值
function generateCascaderFieldList(xAxisRelations, linkageInfo) {
  const { name } = linkageInfo;
  // 多维度 多选
  if(isArray(name[0])) {
    const fieldMap = [];
    const fieldMapItem = {};
    name.forEach(nameItem => {
      xAxisRelations.forEach((item, index) => {
        const filter = formatFilterItem(item);
        if (!fieldMapItem[item.datasetFieldName]) {
          fieldMapItem[item.datasetFieldName] = {
            value: [nameItem[index]] || '', // name存在没有选择的数据情况
            dateFormat: filter?.dateFormat || '',
            active: true
          };
        } else {
          fieldMapItem[item.datasetFieldName].value.push(nameItem[index]);
        }
      })
    })
    fieldMap.push(fieldMapItem)
    return Promise.resolve(fieldMap, linkageInfo);
  }
  // 多维度 单选
  const fieldMap = {};
  xAxisRelations.forEach((item, index) => {
    const filter = formatFilterItem(item);
    fieldMap[item.datasetFieldName] = {
      value: name[index] || '',
      dateFormat: filter?.dateFormat || '',
      active: true
    };
  });
  return Promise.resolve(fieldMap, linkageInfo);
}

// 树形选择器需要映射的值
function generateTreeSelectFieldList(linkageInfo) {
  const { values, seriesType } = linkageInfo;
  const fieldMap = {
    [seriesType]: {
      value: values,
      active: true
    }
  }
  return Promise.resolve(fieldMap, linkageInfo);
}

// 联动器
function generateControlLinkageFieldList(xAxisRelations, linkageInfo) {
  const { values } = linkageInfo;
  const fieldMap = {};
  // 多维度
  xAxisRelations.forEach((item) => {
    const filter = formatFilterItem(item);
    fieldMap[item.datasetFieldName] = {
      value: values[item.datasetFieldName]?.value,
      dateFormat: filter?.dateFormat || '',
      active: true
    };
  });
  return Promise.resolve(fieldMap, linkageInfo);
}
